<script lang="ts">
	import { createMessage } from '$components/basic/message';
	import Button from '@smui/button';
	import { onMount } from 'svelte';
	import Aside from './_com/Aside.svelte';
	import PreviewList from './_com/PreviewList.svelte';
	import { STATIC_API } from '@/api/constant.api';
	import { useCommonPageInit as useSideOptionsInit, type InitOptions } from '@/hooks/pageInit';
	import { useCommonPageInit } from '@/hooks/pageInit';
	import { debounce } from '$utils/debounce';
	import { entries } from 'lodash-es';
	import { useNavBarStore } from '@/store/modules/navBar';
	import ContentLoading from '$components/basic/loading/ContentLoading.svelte';

	let app: HTMLElement | null;
	onMount(() => (app = document.getElementById('app')));
	const scrollToTop = () => app?.scrollTo({ top: 0, behavior: 'smooth' });

	// createMessage({ loading: true, message: 'hello world' })
	let checkedLists: { [key: string]: string[] } = {};
	let page = 1;
	let total = 1;
	const handle = (data, initList) => {
		checkedLists = Object.keys(data).reduce((acc, name) => ({ ...acc, [name]: [] }), {});
		initList(data);
	};
	const options: InitOptions = {
		isInit: true,
		type: 'get',
		handle,
		persist: 'svelte-store:sideOptions'
	};
	const { pageData: list, loading: loadingSide } = useSideOptionsInit<IObject>(
		STATIC_API.GET_PRO_SELECT,
		options
	);
	const handle_products = (data, initList) => {
		page = data.page;
		total = data.total;
		initList(data.list);
	};
	type ReqParams = { price_max: number | string; price_min: number | string } & IObject;
	const params: ReqParams = {
		page: '',
		size: 20,
		sort: '',
		category_id: '',
		category_name: '',
		itemType: '',
		price_min: '',
		price_max: '',
		keyword: '',
		eta: '',
		vision: '',
		newly: ''
	};
	const data_ops: InitOptions = {
		isInit: false,
		loadingInitial: true,
		type: 'post',
		handle: handle_products,
		params
	};
	const {
		list: cartList,
		loading,
		error,
		query
	} = useCommonPageInit<IObject>(STATIC_API.POST_CART_LIST, data_ops);

	const transformListKeyToParamsKey = (key: string) => {
		switch (key) {
			case 'Category':
				return 'category_name';
			case 'ETA':
				return 'eta';
			case 'vision':
				return 'vision';
			case 'Newly Added':
				return 'newly';
			case 'Type':
				return 'itemType';
			default:
				return key;
		}
	};

	const handlePrice = () => {
		if (!checkedLists['Price'] || !checkedLists['Price'].length) return;
		const priceStr = checkedLists['Price'][0];
		const result = { price_max: '', price_min: '' };
		if (priceStr === 'Under $25') Object.assign(result, { price_max: 25 });
		if (priceStr === '$26 - $75') Object.assign(result, { price_min: 26, price_max: 75 });
		if (priceStr === '$76 - $150') Object.assign(result, { price_min: 76, price_max: 150 });
		if (priceStr === '$150+') Object.assign(result, { price_min: 150 });
		Object.assign(params, result);
	};

	const resetKeyWord = () => {
		params.keyword = '';
		navStore.keyword!.update(() => '');
	};
	const resetPage = () => (params.page = 1);
	const mergeSideParams = () =>
		// 合并侧边栏参数
		entries(checkedLists).forEach(([key, value]) => {
			const paramsKey = transformListKeyToParamsKey(key);
			if (typeof params[paramsKey] === 'string' || typeof params[paramsKey] === 'number') {
				params[paramsKey] = value.join('');
			}
		});

	const queryData = debounce(
		// TODO: 请求数据
		async (fn?: () => void) => {
			mergeSideParams();
			handlePrice();
			scrollToTop();
			await query();
			fn && fn();
		},
		300
	);
	let isHandleSide = false; // 是否是侧边栏操作
	const listenChecked = () => {
		isHandleSide = true;
		resetKeyWord();
		resetPage();
		queryData(() => (isHandleSide = false));
	};

	const pageNavigationChange = (event: CustomEvent) => {
		Object.assign(params, event.detail);
		scrollToTop();
		queryData();
	};

	const clearCateParams = () => {
		Object.keys(checkedLists).forEach((key) => {
			checkedLists[key] = [];
		});
		Object.keys(params).forEach((key) => {
			if (key !== 'size') {
				params[key] = '';
			}
		});
	};

	const navStore = useNavBarStore();
	const listenKeyWord = () =>
		navStore.keyword!.subscribe((keyword) => {
			if (isHandleSide) return;
			clearCateParams();
			params.keyword = keyword;
			resetPage();
			queryData();
		});
	onMount(listenKeyWord);
</script>

<!-- 商品分类 -->
<div class="all-products flex-cc h-full w-full flex">
	<ContentLoading
		on:request={() => query()}
		class="w-360px bg-gray-1 h-full border border-b-solid border-gray-2 p-3"
		loading={$loadingSide}
	>
		<Aside list={$list} bind:checkedLists on:action={listenChecked} />
	</ContentLoading>
	<PreviewList
		loading={$loading}
		error={$error}
		list={$cartList}
		bind:total
		bind:page
		on:queryData={pageNavigationChange}
	/>
</div>
